<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>09_form</title>
</head>
<body>
<div id="example"></div>

<script type="text/javascript" src="../js/react.development.js"></script>
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<script type="text/javascript" src="../js/babel.min.js"></script>
<script type="text/babel">
    /*
    需求: 自定义包含表单的组件
      1. 界面如下所示
      2. 输入用户名密码后, 点击登陆提示输入信息
      3. 不提交表单
    */

    // 组件
    class LoginForm extends React.Component {
        constructor(props) {
            super(props);

            // 初始化转态
            this.state={
                pwd:''
            }
            this.handleSubmit = this.handleSubmit.bind(this);
            this.handleChange = this.handleChange.bind(this);
        }

        handleSubmit(event) {
            // 获取用户名和密码
            const uname = this.usernameInput.value.trim();
            const pwd = this.state.pwd.trim();

            // 提示输入的信息
            alert(`准备提交的用户名为${uname},密码为${pwd}`);

            // 阻止事件的默认行为
            event.preventDefault();
        }
        // 原生的dom 的onChange是在失去焦点就触发，react里面的onChange是输入就触发
        handleChange(event) {
            // 读取输入的值
            const pwd = event.target.value;
            // 更新状态
            this.setState({pwd});

        }

        render() {
            return (
                <form action="" method="post" onSubmit={this.handleSubmit}>
                    用户名：<input type="text" name="username" ref={(input) => this.usernameInput = input}/> &nbsp; &nbsp;
                    密码 <input type="password" value={this.state.pwd} onChange={this.handleChange}/>&nbsp; &nbsp;
                    <input type="submit" value="登录"/>
                </form>
            )
        }
    }

    // 渲染组件标签
    ReactDOM.render(<LoginForm/>, document.getElementById("example"));
</script>
</body>
</html>
